package com.shoothzj.example.storage.h2;

import com.shoothzj.example.storage.api.module.FieldInfo;
import com.shoothzj.example.storage.api.module.TableInfo;

import java.util.List;
import java.util.stream.Collectors;

public class H2SqlUtil {
    public static String getDdl(String schemaName, String tableName, TableInfo tableInfo) {
        final StringBuilder sb = new StringBuilder("CREATE TABLE ").append(schemaName).append('.')
                .append(tableName).append("(\n");
        final String collectPrimary = tableInfo.getPrimaryFieldInfos().stream().map(primaryFieldInfo -> {
            String fieldType = H2Util.getFieldType(primaryFieldInfo);
            return primaryFieldInfo.getDbFieldName() + " " + fieldType;
        }).collect(Collectors.joining(",\n"));
        final List<FieldInfo> regularFieldInfos = tableInfo.getRegularFieldInfos();
        if (regularFieldInfos == null || regularFieldInfos.isEmpty()) {
            sb.append(collectPrimary).append(");");
            return sb.toString();
        }
        final String collectRegular = regularFieldInfos.stream().map(fieldInfo -> {
            String fieldType = H2Util.getFieldType(fieldInfo);
            return fieldInfo.getDbFieldName() + " " + fieldType;
        }).collect(Collectors.joining(",\n"));
        sb.append(collectPrimary).append(",\n").append(collectRegular).append(");");
        return sb.toString();
    }
}
